// 导入Redux Toolkit的核心功能
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
// 导入自定义的API请求工具
import request from '../api/request';
// 导入查询字符串处理库
import qs from 'qs';

/**
 * 关注医生的异步action
 * 
 * 功能：向服务器发送关注医生的请求
 * 
 * @param {Object} params - 请求参数
 * @param {string} params.id - 医生ID
 * @param {string} params.doctorflag - 医生标识
 * @returns {Promise} 返回关注操作的响应结果
 */
export const followDoctor = createAsyncThunk(
  'doctor/followDoctor',
  async ({ id, doctorflag }: { id: string; doctorflag: string }) => {
    try {
      const response = await request.post('/doctor/flag', {
        id,
        doctorflag
      });
      return response.data;
    } catch (error) {
      throw error;
    }
  }
);

/**
 * 取消关注医生的异步action
 * 
 * 功能：向服务器发送取消关注医生的请求
 * 
 * @param {Object} params - 请求参数
 * @param {string} params.id - 医生ID
 * @param {string} params.doctorflag - 医生标识
 * @returns {Promise} 返回取消关注操作的响应结果
 */
export const unfollowDoctor = createAsyncThunk(
  'doctor/unfollowDoctor',
  async ({ id, doctorflag }: { id: string; doctorflag: string }) => {
    try {
      const response = await request.post('/doctor/flag', {
        id,
        doctorflag
      });
      return response.data;
    } catch (error) {
      throw error;
    }
  }
);

/**
 * 获取评论标签的异步action
 * 
 * 功能：从服务器获取评论分类标签
 * 
 * @returns {Promise<Array>} 返回评论标签数组
 */
export const fetchReviewTags = createAsyncThunk(
  'doctor/fetchReviewTags',
  async () => {
    try {
      const response = await request.get('/review/classify');
      return response.data?.data || [];
    } catch (error) {
      throw error;
    }
  }
);

/**
 * 获取评论列表的异步action
 * 
 * 功能：根据医生ID获取该医生的评论列表
 * 
 * @param {string} doctorId - 医生ID
 * @returns {Promise<Array>} 返回评论列表数组
 */
export const fetchReviews = createAsyncThunk(
  'doctor/fetchReviews',
  async (doctorId: string) => {
    try {
      const response = await request.get('/review/list', {
        params: { id: doctorId }
      });
      return response.data?.data || [];
    } catch (error) {
      throw error;
    }
  }
);

/**
 * 获取锦旗列表的异步action
 * 
 * 功能：从服务器获取锦旗数据，如果API失败则使用默认数据
 * 
 * @returns {Promise<Array>} 返回锦旗列表数组
 */
export const fetchBanners = createAsyncThunk(
  'doctor/fetchBanners',
  async () => {
    try {
      const response = await request.get('/review/banner');
      if (response.data && response.data.data) {
        return response.data.data;
      } else {
        // 如果API没有返回数据，使用扩展的默认锦旗数据
        return [
          { state: '医术精湛', image: 'http://example.com/banner1.jpg' },
          { state: '医德高尚', image: 'http://example.com/banner2.jpg' },
          { state: '妙手回春', image: 'http://example.com/banner3.jpg' },
          { state: '仁心仁术', image: 'http://example.com/banner4.jpg' },
          { state: '悬壶济世', image: 'http://example.com/banner5.jpg' },
          { state: '华佗再世', image: 'http://example.com/banner6.jpg' },
          { state: '药到病除', image: 'http://example.com/banner7.jpg' },
          { state: '国医圣手', image: 'http://example.com/banner8.jpg' },
          { state: '杏林春暖', image: 'http://example.com/banner9.jpg' },
          { state: '济世救人', image: 'http://example.com/banner10.jpg' },
          { state: '医者仁心', image: 'http://example.com/banner11.jpg' },
          { state: '妙手仁心', image: 'http://example.com/banner12.jpg' },
          { state: '回春妙手', image: 'http://example.com/banner13.jpg' },
          { state: '仁心济世', image: 'http://example.com/banner14.jpg' },
          { state: '医术超群', image: 'http://example.com/banner15.jpg' },
          { state: '医德双馨', image: 'http://example.com/banner16.jpg' }
        ];
      }
    } catch (error) {
      // 使用扩展的默认锦旗数据
      return [
        { state: '医术精湛', image: 'http://example.com/banner1.jpg' },
        { state: '医德高尚', image: 'http://example.com/banner2.jpg' },
        { state: '妙手回春', image: 'http://example.com/banner3.jpg' },
        { state: '仁心仁术', image: 'http://example.com/banner4.jpg' },
        { state: '悬壶济世', image: 'http://example.com/banner5.jpg' },
        { state: '华佗再世', image: 'http://example.com/banner6.jpg' },
        { state: '药到病除', image: 'http://example.com/banner7.jpg' },
        { state: '国医圣手', image: 'http://example.com/banner8.jpg' },
        { state: '杏林春暖', image: 'http://example.com/banner9.jpg' },
        { state: '济世救人', image: 'http://example.com/banner10.jpg' },
        { state: '医者仁心', image: 'http://example.com/banner11.jpg' },
        { state: '妙手仁心', image: 'http://example.com/banner12.jpg' },
        { state: '回春妙手', image: 'http://example.com/banner13.jpg' },
        { state: '仁心济世', image: 'http://example.com/banner14.jpg' },
        { state: '医术超群', image: 'http://example.com/banner15.jpg' },
        { state: '医德双馨', image: 'http://example.com/banner16.jpg' }
      ];
    }
  }
);

/**
 * 提交评论的异步action
 * 
 * 功能：向服务器提交新的评论或锦旗
 * 
 * @param {Object} params - 请求参数
 * @param {Object} params.reviewData - 评论或锦旗数据
 * @param {string} params.doctorId - 医生ID
 * @returns {Promise} 返回提交操作的响应结果
 */
export const submitReview = createAsyncThunk(
  'doctor/submitReview',
  async ({ reviewData, doctorId }: { reviewData: any; doctorId: string }) => {
    try {
      const data = qs.stringify({
        name: reviewData.name,
        title: reviewData.title,
        doctorid: doctorId,
        state: Array.isArray(reviewData.tags) ? reviewData.tags.join(',') : reviewData.tags,
        good: reviewData.rating.toString()
      });
      
      const response = await request.put('/review/list', data, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      });
      
      return { response: response.data, reviewData };
    } catch (error) {
      throw error;
    }
  }
);

/**
 * 赠送锦旗的异步action
 * 
 * 功能：向服务器赠送新的锦旗
 * 
 * @param {Object} params - 请求参数
 * @param {Object} params.bannerData - 锦旗数据
 * @param {string} params.doctorId - 医生ID
 * @returns {Promise} 返回赠送操作的响应结果
 */
export const sendBanner = createAsyncThunk(
  'doctor/sendBanner',
  async ({ bannerData, doctorId }: { bannerData: any; doctorId: string }) => {
    try {
      const data = qs.stringify({
        name: bannerData.name,
        image: bannerData.image,
        state: bannerData.state,
        timer: bannerData.timer,
        doctorid: doctorId
      });
      
      const response = await request.post('/review/banview', data, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      });
      
      return { response: response.data, bannerData };
    } catch (error) {
      throw error;
    }
  }
);

/**
 * 获取医生详情的异步action
 * 
 * 功能：根据医生ID获取该医生的详细信息
 * 
 * @param {string} doctorId - 医生ID
 * @returns {Promise<Object>} 返回医生详情对象
 */
export const fetchDoctorDetail = createAsyncThunk(
  'doctor/fetchDoctorDetail',
  async (doctorId: string) => {
    try {
      const response = await request.get('/doctor/detail', {
        params: { id: doctorId }
      });
      
      if (response.data && response.data.data && Array.isArray(response.data.data) && response.data.data.length > 0) {
        // API返回的是数组，取第一个匹配的医生
        const doctorDetail = response.data.data.find((doctor: { doctorid?: string | number; id?: string | number }) => 
          doctor.doctorid == doctorId || doctor.id == doctorId
        );
        
        if (doctorDetail) {
          return doctorDetail;
        } else {
          throw new Error('未找到医生详情');
        }
      } else {
        throw new Error('API未返回医生数据');
      }
    } catch (error) {
      throw error;
    }
  }
);

/**
 * 获取医生列表的异步action
 * 
 * 功能：根据科室ID和分页参数获取医生列表
 * 
 * @param {Object} params - 请求参数
 * @param {string} params.departmentId - 科室ID
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页数量
 * @returns {Promise<Array>} 返回医生列表数组
 */
export const fetchDoctors = createAsyncThunk(
  'doctor/fetchDoctors',
  async ({ departmentId, page = 1, pageSize = 10 }: { departmentId?: string; page?: number; pageSize?: number }) => {
    try {
      const params: any = { page, pageSize };
      if (departmentId) {
        params.departmentId = departmentId;
      }
      
      const response = await request.get('/doctor/list', { params });
      return response.data?.data || [];
    } catch (error) {
      throw error;
    }
  }
);

/**
 * 医生接口定义
 * 
 * 用于描述医生对象的结构
 */
interface Doctor {
  id: string;
  name: string;
  title: string;
  hospital: string;
  department: string;
  avatar: string;
  isOnline: boolean;
  consultationMethods: string[];
  specialties: string;
  rating: number;
  commendations: number;
  views: number;
  price: number;
  isGradeA?: boolean;
}

/**
 * 评论接口定义
 * 
 * 用于描述评论对象的结构
 */
interface Review {
  name: string;
  title: string;
  good: number;
  state: string | string[];
  timer?: string;
  avatar?: string;
  replies?: Array<{
    replierName: string;
    content: string;
    timer: string;
    avatar?: string;
  }>;
}

/**
 * 锦旗接口定义
 * 
 * 用于描述锦旗对象的结构
 */
interface Banner {
  state: string;
  image: string;
  name?: string;
  timer?: string;
}

/**
 * 医生状态接口定义
 * 
 * 用于描述医生相关状态的结构
 */
interface DoctorState {
  followedDoctors: string[]; // 已关注医生的ID列表
  followedDoctorsData: Doctor[]; // 已关注医生的完整数据
  reviews: Review[]; // 评论列表
  banners: Banner[]; // 锦旗列表
  reviewTags: Array<{classifyid: string; classifytitle: string}>; // 评论标签
  currentDoctor: Doctor | null; // 当前查看的医生详情
  doctorsList: Doctor[]; // 医生列表
  doctorsLoading: boolean; // 医生列表加载状态
  doctorDetailLoading: boolean; // 医生详情加载状态
  loading: boolean; // 通用加载状态
  error: string | null; // 错误信息
}

/**
 * 初始状态定义
 * 
 * 设置医生相关状态的初始值
 */
const initialState: DoctorState = {
  followedDoctors: [], // 空数组：已关注医生ID列表
  followedDoctorsData: [], // 空数组：已关注医生完整数据
  reviews: [], // 空数组：评论列表
  banners: [], // 空数组：锦旗列表
  reviewTags: [], // 空数组：评论标签
  currentDoctor: null, // null：当前查看的医生详情
  doctorsList: [], // 空数组：医生列表
  doctorsLoading: false, // false：医生列表加载状态
  doctorDetailLoading: false, // false：医生详情加载状态
  loading: false, // false：通用加载状态
  error: null, // null：错误信息
};

/**
 * 医生Slice配置
 * 
 * 管理医生相关的所有状态和操作
 */
const doctorSlice = createSlice({
  name: 'doctor', // slice名称
  initialState, // 初始状态
  reducers: {
    /**
     * 添加关注的医生（包含完整数据）
     * 
     * 功能：将医生添加到关注列表，避免重复添加
     * 
     * @param {DoctorState} state - 当前状态
     * @param {Object} action - action对象
     * @param {Doctor} action.payload - 要关注的医生数据
     */
    addFollowedDoctor: (state, action: { payload: Doctor }) => {
      const doctor = action.payload;
      if (!state.followedDoctors.includes(doctor.id)) {
        state.followedDoctors.push(doctor.id);
        state.followedDoctorsData.push(doctor);
      }
    },
    
    /**
     * 移除关注的医生
     * 
     * 功能：从关注列表中移除指定医生
     * 
     * @param {DoctorState} state - 当前状态
     * @param {Object} action - action对象
     * @param {string} action.payload - 要取消关注的医生ID
     */
    removeFollowedDoctor: (state, action: { payload: string }) => {
      const doctorId = action.payload;
      state.followedDoctors = state.followedDoctors.filter(id => id !== doctorId);
      state.followedDoctorsData = state.followedDoctorsData.filter(doctor => doctor.id !== doctorId);
    },
    
    /**
     * 添加新评论到本地状态
     * 
     * 功能：将新提交的评论添加到本地评论列表
     * 
     * @param {DoctorState} state - 当前状态
     * @param {Object} action - action对象
     * @param {Review} action.payload - 新评论数据
     */
    addReview: (state, action: { payload: Review }) => {
      state.reviews.push(action.payload);
    },
    
    /**
     * 添加新锦旗到本地状态
     * 
     * 功能：将新赠送的锦旗添加到本地锦旗列表
     * 
     * @param {DoctorState} state - 当前状态
     * @param {Object} action - action对象
     * @param {Banner} action.payload - 新锦旗数据
     */
    addBanner: (state, action: { payload: Banner }) => {
      state.banners.push(action.payload);
    },
    
    /**
     * 更新评论的回复
     * 
     * 功能：为指定评论添加新的回复
     * 
     * @param {DoctorState} state - 当前状态
     * @param {Object} action - action对象
     * @param {Object} action.payload - 回复数据
     * @param {number} action.payload.reviewIndex - 评论索引
     * @param {Object} action.payload.reply - 回复内容
     */
    updateReviewReplies: (state, action: { payload: { reviewIndex: number; reply: { replierName: string; content: string; timer: string } } }) => {
      const { reviewIndex, reply } = action.payload;
      if (state.reviews[reviewIndex]) {
        if (!state.reviews[reviewIndex].replies) {
          state.reviews[reviewIndex].replies = [];
        }
        state.reviews[reviewIndex].replies!.push(reply);
      }
    },
    
    /**
     * 清空错误信息
     * 
     * 功能：清除当前错误状态
     * 
     * @param {DoctorState} state - 当前状态
     */
    clearError: (state) => {
      state.error = null;
    },
    
    /**
     * 设置当前医生详情
     * 
     * 功能：设置当前正在查看的医生信息
     * 
     * @param {DoctorState} state - 当前状态
     * @param {Object} action - action对象
     * @param {Doctor|null} action.payload - 医生详情数据或null
     */
    setCurrentDoctor: (state, action: { payload: Doctor | null }) => {
      state.currentDoctor = action.payload;
    },
    
    /**
     * 清空当前医生详情
     * 
     * 功能：清除当前查看的医生信息
     * 
     * @param {DoctorState} state - 当前状态
     */
    clearCurrentDoctor: (state) => {
      state.currentDoctor = null;
    },
    
    /**
     * 设置医生列表
     * 
     * 功能：更新医生列表数据
     * 
     * @param {DoctorState} state - 当前状态
     * @param {Object} action - action对象
     * @param {Doctor[]} action.payload - 医生列表数组
     */
    setDoctorsList: (state, action: { payload: Doctor[] }) => {
      state.doctorsList = action.payload;
    },
    
    /**
     * 添加医生到列表
     * 
     * 功能：将医生添加到列表中，如果已存在则更新
     * 
     * @param {DoctorState} state - 当前状态
     * @param {Object} action - action对象
     * @param {Doctor} action.payload - 医生数据
     */
    addDoctorToList: (state, action: { payload: Doctor }) => {
      // 确保 doctorsList 是数组
      if (!Array.isArray(state.doctorsList)) {
        state.doctorsList = [];
      }
      
      const existingIndex = state.doctorsList.findIndex(d => d.id === action.payload.id);
      if (existingIndex >= 0) {
        state.doctorsList[existingIndex] = action.payload;
      } else {
        state.doctorsList.push(action.payload);
      }
    },
  },
  extraReducers: (builder) => {
    builder
      // 关注医生
      .addCase(followDoctor.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(followDoctor.fulfilled, (state, action) => {
        state.loading = false;
      })
      .addCase(followDoctor.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '关注失败';
      })
      // 取消关注医生
      .addCase(unfollowDoctor.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(unfollowDoctor.fulfilled, (state, action) => {
        state.loading = false;
      })
      .addCase(unfollowDoctor.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '取消关注失败';
      })
      // 获取评论标签
      .addCase(fetchReviewTags.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchReviewTags.fulfilled, (state, action) => {
        state.loading = false;
        state.reviewTags = action.payload;
      })
      .addCase(fetchReviewTags.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取评论标签失败';
      })
      // 获取评论列表
      .addCase(fetchReviews.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchReviews.fulfilled, (state, action) => {
        state.loading = false;
        state.reviews = action.payload;
      })
      .addCase(fetchReviews.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取评论列表失败';
      })
      // 获取锦旗列表
      .addCase(fetchBanners.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchBanners.fulfilled, (state, action) => {
        state.loading = false;
        state.banners = action.payload;
      })
      .addCase(fetchBanners.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取锦旗列表失败';
      })
      // 提交评论
      .addCase(submitReview.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(submitReview.fulfilled, (state, action) => {
        state.loading = false;
        // 检查是否成功
        const { response, reviewData } = action.payload;
        if (response && (
          response.success === true || 
          response.code === 200 || 
          response.code === 20000 ||
          response.status === 'success' ||
          response.message === 'success' ||
          response.msg === '评论成功' ||
          response.msg === '锦旗赠送成功'
        )) {
          // 添加新评论到本地状态
          const newReview: Review = {
            name: reviewData.name,
            title: reviewData.title,
            good: reviewData.rating,
            state: Array.isArray(reviewData.tags) ? reviewData.tags : [reviewData.tags],
            timer: new Date().toISOString().split('T')[0]
          };
          state.reviews.push(newReview);
        }
      })
      .addCase(submitReview.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '提交评论失败';
      })
      // 赠送锦旗
      .addCase(sendBanner.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(sendBanner.fulfilled, (state, action) => {
        state.loading = false;
        // 检查是否成功
        const { response, bannerData } = action.payload;
        if (response && (
          response.success === true || 
          response.code === 200 || 
          response.code === 20000 ||
          response.status === 'success' ||
          response.message === 'success' ||
          response.msg === '评论成功' ||
          response.msg === '锦旗赠送成功'
        )) {
          // 添加新锦旗到本地状态
          const newBanner: Banner = {
            state: bannerData.state,
            image: bannerData.image,
            name: bannerData.name,
            timer: bannerData.timer
          };
          state.banners.push(newBanner);
        }
      })
      .addCase(sendBanner.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '赠送锦旗失败';
      })
      // 获取医生详情
      .addCase(fetchDoctorDetail.pending, (state) => {
        state.doctorDetailLoading = true;
        state.error = null;
      })
      .addCase(fetchDoctorDetail.fulfilled, (state, action) => {
        state.doctorDetailLoading = false;
        state.currentDoctor = action.payload;
      })
      .addCase(fetchDoctorDetail.rejected, (state, action) => {
        state.doctorDetailLoading = false;
        state.error = action.error.message || '获取医生详情失败';
      })
      // 获取医生列表
      .addCase(fetchDoctors.pending, (state) => {
        state.doctorsLoading = true;
        state.error = null;
      })
      .addCase(fetchDoctors.fulfilled, (state, action) => {
        state.doctorsLoading = false;
        state.doctorsList = action.payload;
      })
      .addCase(fetchDoctors.rejected, (state, action) => {
        state.doctorsLoading = false;
        state.error = action.error.message || '获取医生列表失败';
      });
  },
});

export const { 
  addFollowedDoctor, 
  removeFollowedDoctor, 
  addReview,
  addBanner,
  updateReviewReplies,
  clearError,
  setCurrentDoctor,
  clearCurrentDoctor,
  setDoctorsList,
  addDoctorToList
} = doctorSlice.actions;

export type { Review, Banner, Doctor };

export default doctorSlice.reducer; 